import { plainToInstance } from 'class-transformer';

export * from './validate'

/** 对象键转驼峰 */
export function objToCamelCase(obj: Record<string, any>) {
  let resultObj: Record<string, any> = {};
  for (let key in obj) {
    let newKey = key[0].toLowerCase() + key.slice(1).replace(/_([a-z])/g, function($0,$1){return $1.toUpperCase();});
    resultObj[newKey] = obj[key];
  }
  return resultObj
}

/** 数组转驼峰 */
export function arrToCamelCase(arr: any[]) {
  return arr.map(item => objToCamelCase(item))
}

/** 驼峰转下划线 */
export function getKebabCase(str: string) {
  let temp = str.replace(/[A-Z]/g, function(i) {
      return '_' + i.toLowerCase();
  })
  if (temp.slice(0,1) === '_') {
      temp = temp.slice(1);   //如果首字母是大写，执行replace时会多一个_，需要去掉
  }
  return temp;
}

/** 对象转驼峰转下划线 */
export function objectToKebabCase(obj: Record<string, any>) {
  const output: Record<string, any> = {};
  for (let key in obj) {
    const item = obj[key];
    output[getKebabCase(key)] = item;
  }

  return output
}

export function getDateTimeDiff(source: Date, target: Date) {
  const sourceDate = new Date(source).getTime();
  const targetDate = new Date(target).getTime();

  const diff = targetDate - sourceDate;
  const datetime = 1000 * 60 * 60;
  const hour = Math.floor(diff / datetime);
  const minite = Math.floor(diff % datetime / 60000);
  const second = Math.floor(datetime % 60000 / 1000);

  return `${hour.toString().padStart(2, '0')}:${minite.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`
}

/** 设置对象属性值到类中 */
export function setObjAttrToCls<T>(instance: T, cls: any, data: any) {
  return Object.assign(instance, plainToInstance(cls, data))
}
